package com.kiragame.xchat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import net.simonvt.menudrawer.MenuDrawer;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.provider.Settings;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.LayoutParams;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.androidquery.util.AQUtility;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.kiragame.xchat.adapter.ChatPrivateAdapter;
import com.kiragame.xchat.adapter.ChatRoomAdapter;
import com.kiragame.xchat.adapter.EmoticonAdapter;
import com.kiragame.xchat.adapter.HistoryMessageAdapter;
import com.kiragame.xchat.adapter.UserAdapter;
import com.kiragame.xchat.database.MessagesDataManager;
import com.kiragame.xchat.fragment.ChooseImageDialogFragment;
import com.kiragame.xchat.fragment.ChooseImageDialogFragment.OnChooseImageDialogFragment;
import com.kiragame.xchat.fragment.EditProfileDialogFragment;
import com.kiragame.xchat.fragment.ExitConfirmDialogFragment;
import com.kiragame.xchat.fragment.ExitConfirmDialogFragment.OnExitDialogListener;
import com.kiragame.xchat.fragment.RateAppDialogFragment;
import com.kiragame.xchat.fragment.SayHiDialogFragment;
import com.kiragame.xchat.fragment.SayHiDialogFragment.OnSayHiDialogFragment;
import com.kiragame.xchat.fragment.SettingDialogFragment;
import com.kiragame.xchat.object.HideChatBarState;
import com.kiragame.xchat.object.HistoryMessage;
import com.kiragame.xchat.object.MainDisplayState;
import com.kiragame.xchat.object.MessageContent;
import com.kiragame.xchat.object.MessageContent.MsgType;
import com.kiragame.xchat.object.RoomType;
import com.kiragame.xchat.object.SaveStateConfig;
import com.kiragame.xchat.object.User;
import com.kiragame.xchat.object.UserInfo;
import com.kiragame.xchat.service.ChatService;
import com.kiragame.xchat.utils.Common;
import com.kiragame.xchat.utils.DataManager;
import com.kiragame.xchat.utils.Emoticons;
import com.kiragame.xchat.utils.KiraGameLog;
import com.kiragame.xchat.utils.Utils;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelSlideListener;

public class MainActivity extends SherlockFragmentActivity {

	// FLOWS: SETUP SERVER -> CHECK PROFILE AND UPDATE -> JOIN ROOM -> LOAD USER
	// -> FIND CHAT PARTNER
	// IN ROOM
	// Layout
	private MenuDrawer mDrawerMessages;
	private ActionBar mActionBar;

	private ListView lvChat;
	private LinearLayout llSendMessage;
	private EditText etMessage;
	private ImageButton btSend;
	private ListView lvUsers;
	private GridView gvEmoticons;
	private ImageButton btEmoticon;
	private ImageButton btImage;
	private SlidingUpPanelLayout slidingLayout;
	private Button btFindchat;

	// SNACK BAR
	private LinearLayout llNotice;
	private ProgressBar pbLoading;
	private TextView tvNotice;
	private View vSplit;
	private TextView tvAction;
	private Animation animationShow;
	private Animation animationHide;

	// Actionbar
	private ImageButton ibProfile;
	private Spinner snRoom;
	private ImageButton ibHideChat;
	private RelativeLayout rlMessages;
	private ImageButton ibMessages;
	private TextView tvNumMessage;
	private TextView tvTitle;
	private ImageButton ibMark;

	// MESSAGES FRAGMENT
	private ListView lvMessages;
	private Button btLogout;
	private TextView tvNameRoomMessageHistory;
	private TextView tvMessageRoomMessageHistory;
	private TextView tvMessageNumRoomMessageHistory;
	private Button btSetting;
	private LinearLayout llRoomMessageHistory;
	private List<HistoryMessage> historyMessageData = new ArrayList<HistoryMessage>();
	private HistoryMessageAdapter historyMessageAdapter;

	private int newRoomMessageHistory = 0;

	// CHAT IN ROOM
	private List<MessageContent> messageContentRoomData = new ArrayList<MessageContent>();
	private ChatRoomAdapter chatRoomAdapter;

	// USER IN ROOM
	private List<User> userData = new ArrayList<User>();
	private UserAdapter userAdapter;

	// CHAT PRIVATE
	private List<MessageContent> messageContentPrivateData = new ArrayList<MessageContent>();
	private ChatPrivateAdapter chatPrivateAdapter;

	private boolean isInfoUpdating = false;
	private boolean isAcceptUserRoomInfoUpdate = false;
	private boolean isExit = false;

	// COMMON
	private String hideChatUserID = null;
	private String hideChatUserName = null;
	private MainDisplayState mDisplayState = MainDisplayState.ROOM_STATUS;
	private HideChatBarState mHideChatBarState = HideChatBarState.CHAT_ROOM;
	private Vibrator vibrator;

	private boolean isFindingChat = false;

	private RoomType currentRoom;

	private final long FIND_FRIEND_TIME_OUT = 1000 * 30;

	// Saved Instance State
	private final String SAVE_STATE_CONFIG = "SAVE_STATE_CONFIG";

	// private boolean isShowChat = false;
	private AdView mAdViewMain;
	private AdView mAdViewChat;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
		// setContentView(R.layout.splash);
		// getActionBar().hide();
		KiraGameLog.d("-------- onCreate --------");
		// stop service
		// stopService(new Intent(this, ChatService.class));
		settingActionbar();
		settingSlidingMessages();
		findViews();
		init();
		setEvent();
	}

	private void checkViewNotify() {
		Integer userID = DataManager.getInstance(this).getNotifyUserId();
		String userName = DataManager.getInstance(this).getNotifyUserName();

		if (userID != 0 && userName != null) {
			showChatPrivate(Integer.toString(userID), userName, true);
			DataManager.getInstance(this).setNotifyUserId(0);
			DataManager.getInstance(this).setNotifyUserName(null);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		SaveStateConfig config = new SaveStateConfig();
		config.setHideChatUserID(hideChatUserID);
		config.setHideChatUserName(hideChatUserName);
		config.setmDisplayState(mDisplayState);
		config.setmHideChatBarState(mHideChatBarState);

		savedInstanceState.putString(SAVE_STATE_CONFIG, config.toJson());
		KiraGameLog.d("onSaveInstanceState SAVE_STATE_CONFIG: "
				+ config.toJson());
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);

		SaveStateConfig config = SaveStateConfig
				.fromJsonToSaveStateConfig(savedInstanceState
						.getString(SAVE_STATE_CONFIG));

		hideChatUserID = config.getHideChatUserID();
		hideChatUserName = config.getHideChatUserName();
		mDisplayState = config.getmDisplayState();
		mHideChatBarState = config.getmHideChatBarState();

		KiraGameLog.d("onRestoreInstanceState SAVE_STATE_CONFIG: "
				+ config.toJson());

		changeActionBarState(mDisplayState);

		if (mDisplayState == MainDisplayState.CHAT_PRIVATE) {
			showChatPrivate(hideChatUserID, hideChatUserName, true);
		} else if (mDisplayState == MainDisplayState.CHAT_ROOM) {
			showChatRoom();
		} else {
			slidingLayout.collapsePanel();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent itent) {
		super.onActivityResult(requestCode, resultCode, itent);
		switch (requestCode) {
		case Common.RequestCode.LOGIN:
			if (resultCode == RESULT_CANCELED) {
				finish();
			} else {
				startChatService();
			}
			break;
		case Common.RequestCode.CHAT_IMAGE:
			if (resultCode == RESULT_CANCELED) {
				return;
			}
			String url = itent.getStringExtra(ProcessImage.IMAGE_URL);
			sendImageChat(url);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		if (mDrawerMessages.isMenuVisible()) {
			mDrawerMessages.toggleMenu();
		} else if (gvEmoticons.getVisibility() == View.VISIBLE) {
			gvEmoticons.setVisibility(View.GONE);
		} else if (slidingLayout != null && slidingLayout.isPanelExpanded()
				|| slidingLayout.isPanelAnchored()) {
			slidingLayout.collapsePanel();
		} else {
			// super.onBackPressed();
			showExitDialog();
		}
	}

	@Override
	protected void onDestroy() {
		KiraGameLog.d("--------- onDestroy ---------");
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				changeUIReceiver);
		// if (ChatService.getInstance() != null) {
		// ChatService.getInstance().logOut();
		// }
		DataManager.getInstance(MainActivity.this).setIsLogout(false);
		DataManager.getInstance(MainActivity.this).setIsShowPost(false);
		stopService(new Intent(this, ChatService.class));

		if (mAdViewMain != null) {
			mAdViewMain.destroy();
		}

		if (mAdViewChat != null) {
			mAdViewChat.destroy();
		}
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		KiraGameLog.d("--------- onStop ---------");
		super.onStop();
	}

	@Override
	protected void onPause() {
		KiraGameLog.d("--------- onPause ---------");
		DataManager.getInstance(this).setIsShowNotify(true);
		if (mAdViewMain != null) {
			mAdViewMain.pause();
		}

		if (mAdViewChat != null) {
			mAdViewChat.pause();
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		KiraGameLog.d("--------- onResume ---------");
		checkConnection();
		DataManager.getInstance(this).setIsShowNotify(false);
		checkViewNotify();
		if (mDisplayState == MainDisplayState.CHAT_PRIVATE) {
			lvChat.setSelection(messageContentPrivateData.size() - 1);
		} else {
			lvChat.setSelection(messageContentRoomData.size() - 1);
		}

		if (mAdViewMain != null) {
			mAdViewMain.resume();
		}

		if (mAdViewChat != null) {
			mAdViewChat.resume();
		}

	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		KiraGameLog.d("--------- onDetachedFromWindow ---------");
	}

	private void checkConnection() {
		if (ChatService.getInstance() != null) {
			if (!ChatService.getInstance().isLogin()) {
				KiraGameLog.d("Chat service is disconnect, reconnect....");
				ChatService.getInstance().setUpServer();
			} else {
				KiraGameLog.d("Chat service is still connecting....");
			}
		}
	}

	private void settingSlidingMessages() {
		mDrawerMessages = MenuDrawer.attach(this);
		mDrawerMessages.setContentView(R.layout.activity_main);
		mDrawerMessages.setMenuView(getMessagesView());
		mDrawerMessages.setDropShadowColor(Color.parseColor("#ff8800"));
		mDrawerMessages.setDropShadowSize(1);
	}

	private void settingActionbar() {
		View customView = getActionbarView();
		LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		mActionBar = getSupportActionBar();
		mActionBar.setCustomView(customView, layout);
		// mActionBar.hide();
		mActionBar.setDisplayShowHomeEnabled(false);
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayShowCustomEnabled(true);
		mActionBar.setDisplayShowTitleEnabled(false);
		// mActionBar.setCustomView(getActionbarView());
		mActionBar.show();
	}

	private View getActionbarView() {
		View view = getLayoutInflater().inflate(R.layout.actionbar_main, null);
		ibProfile = (ImageButton) view.findViewById(R.id.ib_profile);
		snRoom = (Spinner) view.findViewById(R.id.sn_room);
		rlMessages = (RelativeLayout) view.findViewById(R.id.rl_messages);
		ibMessages = (ImageButton) view.findViewById(R.id.ib_messages);
		tvNumMessage = (TextView) view.findViewById(R.id.tv_num_message);
		ibHideChat = (ImageButton) view.findViewById(R.id.ib_hide_chat);
		tvTitle = (TextView) view.findViewById(R.id.tv_title);
		ibMark = (ImageButton) view.findViewById(R.id.ib_mark);
		return view;
	}

	private void findViews() {
		tvNotice = (TextView) findViewById(R.id.tv_notice);
		lvChat = (ListView) findViewById(R.id.lv_chat);
		llSendMessage = (LinearLayout) findViewById(R.id.ll_send_message);
		etMessage = (EditText) findViewById(R.id.et_message);
		btSend = (ImageButton) findViewById(R.id.bt_send);
		slidingLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
		lvUsers = (ListView) findViewById(R.id.lv_users);
		gvEmoticons = (GridView) findViewById(R.id.gv_emoticons);
		btEmoticon = (ImageButton) findViewById(R.id.bt_emoticon);
		btImage = (ImageButton) findViewById(R.id.bt_image);
		llNotice = (LinearLayout) findViewById(R.id.ll_notice);
		pbLoading = (ProgressBar) findViewById(R.id.pbLoading);
		tvNotice = (TextView) findViewById(R.id.tv_notice);
		vSplit = (View) findViewById(R.id.v_split);
		tvAction = (TextView) findViewById(R.id.tv_action);
		btFindchat = (Button) findViewById(R.id.bt_findchat);
		mAdViewMain = (AdView) findViewById(R.id.adViewMain);
		mAdViewChat = (AdView) findViewById(R.id.adViewChat);
	}

	private void init() {
		changeActionBarState(mDisplayState);
		DataManager.getInstance(this).setCurrentChatUserId(null);
		animationShow = AnimationUtils.loadAnimation(this,
				R.anim.snackbar_show_animation);
		animationHide = AnimationUtils.loadAnimation(this,
				R.anim.snackbar_hide_animation);
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		snRoom.setEnabled(false);
		lvChat.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
		lvChat.setStackFromBottom(true);
		btSend.setEnabled(false);

		// Default display chat room
		chatRoomAdapter = new ChatRoomAdapter(this, messageContentRoomData);
		lvChat.setAdapter(chatRoomAdapter);

		// Switch to chat private
		chatPrivateAdapter = new ChatPrivateAdapter(this,
				messageContentPrivateData);

		userAdapter = new UserAdapter(this, userData);
		lvUsers.setAdapter(userAdapter);

		EmoticonAdapter emoticonAdapter = new EmoticonAdapter(this);
		gvEmoticons.setAdapter(emoticonAdapter);
		slidingLayout.setDragView(new View(this));

		if (!DataManager.getInstance(this).isLogout()) {
			startChatService();
		} else {
			startLoginUI();
		}

		IntentFilter filter = new IntentFilter(ChatService.BROADCAST_NAME_MAIN);
		LocalBroadcastManager.getInstance(this).registerReceiver(
				changeUIReceiver, filter);
		AdRequest adRequest = new AdRequest.Builder().addTestDevice(
				"CD3CF46DD6F23B701659BBF61B94EA51").build();

		// Start loading the ad in the background.
		mAdViewMain.loadAd(adRequest);
		mAdViewChat.loadAd(adRequest);
	}

	private void changeActionBarState(MainDisplayState mainDisplayState) {
		if (mainDisplayState == MainDisplayState.ROOM_STATUS) {
			tvTitle.setText("Online People");
			ibMark.setVisibility(View.GONE);
			ibProfile.setVisibility(View.VISIBLE);
			ibHideChat.setVisibility(View.GONE);
		} else if (mainDisplayState == MainDisplayState.CHAT_PRIVATE) {
			ibMark.setVisibility(View.VISIBLE);
			ibProfile.setVisibility(View.GONE);
			ibHideChat.setVisibility(View.VISIBLE);
		} else if (mainDisplayState == MainDisplayState.CHAT_ROOM) {
			tvTitle.setText("Chat Room");
			ibMark.setVisibility(View.GONE);
			ibProfile.setVisibility(View.GONE);
			ibHideChat.setVisibility(View.VISIBLE);
		}

	}

	private void startLoginUI() {
		Intent intent = new Intent(this, LoginActivity.class);
		startActivityForResult(intent, Common.RequestCode.LOGIN);
	}

	private void setEvent() {
		btSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String message = etMessage.getText().toString();
				etMessage.setText("");
				if (mDisplayState == MainDisplayState.CHAT_ROOM) {
					// Chat room
					ChatService.getInstance().sendMessageChatRoom(message,
							MsgType.TEXT);
					// lvChat.setSelection(chatPrivateAdapter.getCount() - 1);

				} else if (mDisplayState == MainDisplayState.CHAT_PRIVATE) {
					// Chat private
					String chatToUser = DataManager.getInstance(
							MainActivity.this).getCurrentChatUserId();
					if (chatToUser == null) {
						return;
					}
					ChatService.getInstance()
							.sendMessage(Integer.parseInt(chatToUser), message,
									MsgType.TEXT);
					// lvChat.setSelection(chatRoomAdapter.getCount() - 1);
				} else {
					return;
				}
			}
		});

		lvChat.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (mDisplayState == MainDisplayState.CHAT_PRIVATE) {
					return;
				}
				MessageContent messageContent = (MessageContent) parent
						.getAdapter().getItem(position);
				showChatPrivate(
						Integer.toString(messageContent.getFromUserID()),
						messageContent.getName(), false);
			}
		});

		lvUsers.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				User user = (User) parent.getAdapter().getItem(position);
				showChatPrivate(Integer.toString(user.getUserID()),
						user.getName(), false);
			}
		});
		etMessage.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					gvEmoticons.setVisibility(View.GONE);
				}
			}
		});

		etMessage.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (etMessage.getText().toString().trim().length() > 0) {
					btSend.setEnabled(true);
				} else {
					btSend.setEnabled(false);
				}
			}
		});
		gvEmoticons.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				etMessage.append(Emoticons.getSmiledText(MainActivity.this,
						Common.emoticonsName[position]));
			}
		});

		btEmoticon.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gvEmoticons.getVisibility() == View.GONE
						|| gvEmoticons.getVisibility() == View.INVISIBLE) {
					gvEmoticons.setVisibility(View.VISIBLE);
					Utils.hideKeyboard(MainActivity.this, etMessage);
					lvChat.requestFocus();
				} else {
					gvEmoticons.setVisibility(View.GONE);
					etMessage.requestFocus();
					Utils.showKeyboard(MainActivity.this, etMessage);
				}
			}
		});
		slidingLayout.setPanelSlideListener(new PanelSlideListener() {

			@Override
			public void onPanelSlide(View panel, float slideOffset) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPanelHidden(View panel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPanelExpanded(View panel) {
				changeActionBarState(mDisplayState);
			}

			@Override
			public void onPanelCollapsed(View panel) {
				// isShowChat = false;
				mDisplayState = MainDisplayState.ROOM_STATUS;
				Utils.hideKeyboard(MainActivity.this, etMessage);
				changeActionBarState(mDisplayState);

				DataManager.getInstance(MainActivity.this)
						.setCurrentChatUserId(null);
			}

			@Override
			public void onPanelAnchored(View panel) {
				// TODO Auto-generated method stub

			}
		});

		ibHideChat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				slidingLayout.collapsePanel();
				hideDrawerMessages();
			}
		});

		rlMessages.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mDrawerMessages.toggleMenu();
				Utils.hideKeyboard(MainActivity.this, etMessage);
			}
		});

		ibProfile.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				hideDrawerMessages();
				showEditProfileFragment();
			}
		});

		btImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showChooseImageFragment();
			}
		});

		snRoom.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				hideDrawerMessages();
				if (currentRoom.ordinal() == position) {
					return;
				} else {
					currentRoom = RoomType.values()[position];
					DataManager.getInstance(MainActivity.this).setCurrentRoom(
							currentRoom);
					ChatService.getInstance().joinroom(
							Common.listRoom[position]);
					userData.clear();
					messageContentRoomData.clear();
					userAdapter.notifyDataSetChanged();
					chatRoomAdapter.notifyDataSetChanged();

					// Reset new room message num in message fragment
					newRoomMessageHistory = 0;
					tvMessageNumRoomMessageHistory.setVisibility(View.GONE);

					// Update new message num in message fragment
					updateNewMessagesNum();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});

		lvMessages.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				HistoryMessage historyMessage = (HistoryMessage) parent
						.getAdapter().getItem(position);
				showChatPrivate(Integer.toString(historyMessage
						.getMessageContent().getFromUserID()), historyMessage
						.getMessageContent().getName(), false);
			}
		});

		btLogout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// hideDrawerMessages();
				// DataManager.getInstance(MainActivity.this).setIsLogout(true);
				// ChatService.getInstance().logOut();
			}
		});
		llRoomMessageHistory.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showChatRoom();
			}
		});

		btFindchat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				findFriendChat();
			}
		});

		btSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showSettingFragment();
			}
		});

		mAdViewChat.setAdListener(new AdListener() {
			@Override
			public void onAdLoaded() {
				mAdViewChat.setVisibility(View.VISIBLE);
				super.onAdLoaded();
			}

			@Override
			public void onAdFailedToLoad(int errorCode) {
				mAdViewChat.setVisibility(View.GONE);
				super.onAdFailedToLoad(errorCode);
			}
		});

		mAdViewMain.setAdListener(new AdListener() {
			@Override
			public void onAdLoaded() {
				mAdViewMain.setVisibility(View.VISIBLE);
				super.onAdLoaded();
			}

			@Override
			public void onAdFailedToLoad(int errorCode) {
				mAdViewMain.setVisibility(View.GONE);
				super.onAdFailedToLoad(errorCode);
			}
		});

	}

	protected void showChatPrivate(final String userID, final String name,
			boolean isNotify) {
		final Integer userIDInt = Integer.parseInt(userID);
		mDisplayState = MainDisplayState.CHAT_PRIVATE;
		// Update new message num;
		resetUnreadNumMessageFragment(userIDInt);

		hideDrawerMessages();
		String currentChatUserID = DataManager.getInstance(this)
				.getCurrentChatUserId();
		hideChatUserID = userID;
		hideChatUserName = name;
		DataManager.getInstance(this).setCurrentChatUserId(userID);

		if (!isNotify
				&& ((currentChatUserID != null && currentChatUserID
						.equals(userID)) || userIDInt.equals(DataManager
						.getInstance(this).getUserID()))) {
			return;
		}
		// snRoom.setVisibility(View.GONE);
		// tvTitle.setVisibility(View.VISIBLE);
		tvTitle.setText(name);
		changeActionBarState(mDisplayState);

		if (slidingLayout != null && !slidingLayout.isPanelExpanded()) {
			slidingLayout.expandPanel();
		}

		lvChat.setAdapter(chatPrivateAdapter);
		chatPrivateAdapter.clear();
		chatPrivateAdapter.addAll(MessagesDataManager.getInstance(this)
				.getMessages(userID, 0, 10));
		chatPrivateAdapter.notifyDataSetChanged();

		boolean isFriend = MessagesDataManager.getInstance(MainActivity.this)
				.checkIsFriend(userIDInt, name);
		changeButtonMarkState(isFriend);
		ibMark.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MessagesDataManager.getInstance(MainActivity.this).markFriend(
						userIDInt,
						!MessagesDataManager.getInstance(MainActivity.this)
								.checkIsFriend(userIDInt, name));
				boolean isFriend = MessagesDataManager.getInstance(
						MainActivity.this).checkIsFriend(userIDInt, name);
				if (isFriend) {
					ibMark.setImageResource(R.drawable.ic_action_mark_friend);
				} else {
					ibMark.setImageResource(R.drawable.ic_action_toggle_star_outline);
				}

				refreshHistoryMessage();
			}
		});
		refreshHistoryMessage();
	}

	private void changeButtonMarkState(boolean checkIsFriend) {
		if (checkIsFriend) {
			ibMark.setImageResource(R.drawable.ic_action_mark_friend);
		} else {
			ibMark.setImageResource(R.drawable.ic_action_toggle_star_outline);
		}
	}

	protected void refreshHistoryMessage() {
		loadMessageFromDatabase();
	}

	private BroadcastReceiver changeUIReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String actionUIMAin = intent
					.getStringExtra(ChatService.CONTROL_ACTION);
			String message = intent.getStringExtra(ChatService.CONTROL_MESSAGE);
			// KiraGameLog.d("get broadcast receive with action " + actionUIMAin
			// + " and message " + message);
			switch (actionUIMAin) {
			case ChatService.MAIN_ACTION_ON_PRE_SETUP_SERVER:
				onPreSetUpServer();
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_SETUP_SERVER:
				onFinishedSetupServer(message);
				break;
			case ChatService.MAIN_ACTION_ON_PRE_UPDATE_PROFILE:
				onPreUpdateProfile();
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_UPDATE_PROFILE:
				onFinishedUpdateProfile(message);
				break;
			case ChatService.MAIN_ACTION_ON_PRE_JOIN_ROOM:
				onPreJoinRoom();
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_JOIN_ROOM:
				onFinishedJoinRoom(message);
				break;
			case ChatService.MAIN_ACTION_ON_PRE_GET_ROOM_USERS:
				onPreGetRoomUsers();
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_GET_ROOM_USERS_FAIL:
				onFinishedGetRoomUsersFail(message);
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_GET_ROOM_USERS_SUCCESS:
				onFinishedGetRoomUsersSuccess(message);
				break;
			case ChatService.MAIN_ACTION_ON_USER_ENTERED_ROOM:
				onUserEnteredRoom(message);
				break;
			case ChatService.MAIN_ACTION_ON_USER_LEFT_ROOM:
				onUserLeftRoom(message);
				break;
			case ChatService.MAIN_ACTION_ON_PRE_LOG_OUT:
				onPreLogOut();
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_LOG_OUT:
				onFinishedLogOut(message);
				break;

			case ChatService.MAIN_ACTION_ON_PRE_GET_USER_BY_IDS:
				onPreGetUserByIDs();
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_GET_USER_BY_IDS_FAIL:
				onFinishedGetUserByIDsFail(message);
				break;
			case ChatService.MAIN_ACTION_ON_FINISHED_GET_USER_BY_IDS_SUCCESS:
				onFinishedGetUserByIDsSuccess(message);
				break;
			case ChatService.MAIN_ACTION_UPDATE_MESSAGES_IN_CHAT_ROOM_FRAGMENT:
				updateMessageInChatRoom(message);
				break;
			case ChatService.MAIN_ACTION_UPDATE_MESSAGES_IN_MESSAGE_FRAGMENT:
				updateMessageInMessagesFragment(message);
				break;
			case ChatService.MAIN_ACTION_UPDATE_MESSAGES_IN_CHAT_PRIVATE:
				updateListMessageInChatPrivate(message);
				break;
			case ChatService.MAIN_ACTION_NOTIFY_CONNECTION_ONLINE:
				notifyConnectionOnline();
				break;
			case ChatService.MAIN_ACTION_NOTIFY_CONNECTION_OFFLINE:
				notifyConnectionOffline();
				break;
			default:
				break;
			}
		}
	};

	// CALLBACK FROM CHAT SERVICE

	protected void notifyConnectionOffline() {
		KiraGameLog.d("No Internet connection!");
		showNotice(false, "No Internet Connection!", "WIFI SETTING");
		tvAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
				startActivity(intent);
			}
		});
	}

	protected void notifyConnectionOnline() {
		KiraGameLog.d("Internet connection successful!");
		hideNotice();
	}

	protected void onFinishedGetUserByIDsSuccess(String data) {
		updateListUserInRoom(data);
	}

	protected void onFinishedGetUserByIDsFail(String error) {

	}

	protected void onPreGetUserByIDs() {

	}

	protected void onFinishedGetRoomUsersSuccess(String message) {
		userData.clear();
		updateListUserInRoom(message);
		isAcceptUserRoomInfoUpdate = true;
		if (!DataManager.getInstance(this).isShowPost()) {
			showSayHi();
			DataManager.getInstance(this).setIsShowPost(true);
		} else {
			// findFriendChat();
			// sendChatToRoom();
		}
		btFindchat.setVisibility(View.VISIBLE);
		// hideProgessbar();
	}

	protected void onFinishedGetRoomUsersFail(String message) {
		// showNotice(message);
		showNotice(false, message, "RETRY");
		tvAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				hideNotice();
				ChatService.getInstance().getUserOnlineInRoom(1, 100);
			}
		});
		isAcceptUserRoomInfoUpdate = true;
		// hideProgessbar();
	}

	protected void onPreGetRoomUsers() {
		// showProgessbar("Getting online users...");
	}

	protected void onFinishedJoinRoom(String error) {
		if (error != null) {
			// ERROR
			showNotice(false, error, "RETRY");
			// update profile fail. try again?
			tvAction.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					hideNotice();
					ChatService.getInstance().joinroom(
							Common.listRoom[currentRoom.ordinal()]);
				}
			});
		} else {
			// tvNameRoomMessageHistory.setText("Room "
			// + snRoom.getSelectedItem().toString());
			llRoomMessageHistory.setVisibility(View.VISIBLE);
			ChatService.getInstance().getUserOnlineInRoom(1, 100);
		}
		hideNotice();
		snRoom.setEnabled(true);
	}

	protected void onPreJoinRoom() {
		showNotice(true, "Joining room...", null);
		snRoom.setEnabled(false);
		llRoomMessageHistory.setVisibility(View.GONE);
	}

	protected void onFinishedUpdateProfile(String error) {
		hideNotice();
		if (error != null) {
			// ERROR
			showNotice(false, error, "RETRY");
			// update profile fail. try again?
			tvAction.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					hideNotice();
					showEditProfileFragment();
				}
			});
		} else {
			// success
			if (!isInfoUpdating) {
				// findFriendChat();
			}
			updateInfoInRoom();
			sendChatToRoom();
		}
		if (isInfoUpdating) {
			ChatService.getInstance().joinroom(
					Common.listRoom[currentRoom.ordinal()]);
			isInfoUpdating = false;
		}
	}

	protected void onPreUpdateProfile() {
		showNotice(true, "Updating profile...", null);
	}

	protected void onPreSetUpServer() {
		showNotice(true, "Connecting to server...", null);
	}

	protected void onFinishedSetupServer(String error) {
		hideNotice();
		if (error != null) {
			// ERROR
			showNotice(false, error, "RETRY");
			// setup server fail. re setup?
			tvAction.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					hideNotice();
					ChatService.getInstance().setUpServer();
				}
			});
		} else {
			if (!checkProfileAndUpdate()) {
				ChatService.getInstance().joinroom(
						Common.listRoom[currentRoom.ordinal()]);
			}
		}

	}

	protected void onPreLogOut() {
		showNotice(true, "Logout...", null);
	}

	protected void onFinishedLogOut(String error) {
		hideNotice();
		// if (error != null) {
		// // ERROR
		// // showNotice(error);
		// // logout fail. re setup?
		// } else {
		//
		// }
		// DataManager.getInstance(MainActivity.this).setIsShowPost(false);
		// if (isExit) {
		// finish();
		// } else {
		// restartApp();
		// }
	}

	// @SuppressLint("NewApi")
	// private void restartApp() {
	// // if (Build.VERSION.SDK_INT >= 11) {
	// // recreate();
	// // } else {
	// Intent intent = getIntent();
	// intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
	// finish();
	// overridePendingTransition(0, 0);
	// startActivity(intent);
	// overridePendingTransition(0, 0);
	// // }
	// }

	private boolean checkProfileAndUpdate() {
		KiraGameLog.d("check profile is new ?");
		String name = DataManager.getInstance(this).getUserName();
		String status = DataManager.getInstance(this).getUserStatus();
		boolean isNewProfile = ChatService.getInstance().isNewProfile(name,
				status);
		if (isNewProfile) {
			KiraGameLog.d("profile is new, updating profile...");
			isInfoUpdating = true;
			ChatService.getInstance().updateProfile(name, status, null);
		}
		return isNewProfile;
	}

	private void startChatService() {
		// currentRoom = DataManager.getInstance(this).getCurrentRoom();
		currentRoom = RoomType.ADULT;
		snRoom.setSelection(currentRoom.ordinal());

		// if (ChatService.getInstance() != null) {
		// //checkChatServiceConnected();
		// } else {
		Intent service = new Intent(this, ChatService.class);
		startService(service);
		// }
	}

	// ROOM
	private void updateMessageInChatRoom(String message) {
		if (message != null) {
			MessageContent messageContent = MessageContent
					.fromJsonToMessageContent(message);
			if (messageContent.getMsgType() == MsgType.TEXT
					|| messageContent.getMsgType() == MsgType.IMAGE) {
				messageContentRoomData.add(messageContent);
				chatRoomAdapter.notifyDataSetChanged();

				// Update HIDE CHAT BAR
				mHideChatBarState = HideChatBarState.CHAT_ROOM;
				hideChatUserID = Integer.toString(messageContent
						.getFromUserID());
				hideChatUserName = messageContent.getName();

				// Update new message room in Message fragment
				if (mDisplayState != MainDisplayState.CHAT_ROOM) {
					newRoomMessageHistory++;

					if (messageContent.getMsgType() == MsgType.TEXT) {
						tvMessageRoomMessageHistory.setText(Emoticons
								.getSmiledText(this,
										messageContent.getContent()));
					} else {
						tvMessageRoomMessageHistory.setText("Send an image!");
					}

					if (newRoomMessageHistory > 10) {
						tvMessageNumRoomMessageHistory.setText("9+");
						tvMessageNumRoomMessageHistory
								.setVisibility(View.VISIBLE);
					} else if (newRoomMessageHistory > 0) {
						tvMessageNumRoomMessageHistory.setText(String
								.valueOf(newRoomMessageHistory));
						tvMessageNumRoomMessageHistory
								.setVisibility(View.VISIBLE);
					} else {
						tvMessageNumRoomMessageHistory.setVisibility(View.GONE);
					}
					updateNewMessagesNum();
				}

			} else if (messageContent.getMsgType() == MsgType.UPDATE_INFO) {
				updateUserInfoInRoomStatus(User.fromJsonToUser(messageContent
						.getContent()));
			}

		}

	}

	protected void showChatRoom() {
		mDisplayState = MainDisplayState.CHAT_ROOM;

		// Reset new room message num in message fragment
		newRoomMessageHistory = 0;
		tvMessageNumRoomMessageHistory.setVisibility(View.GONE);

		// Update new message num in message fragment
		updateNewMessagesNum();

		// Set coming message go to history message fragment
		DataManager.getInstance(this).setCurrentChatUserId(null);

		changeActionBarState(mDisplayState);

		hideDrawerMessages();
		lvChat.setAdapter(chatRoomAdapter);
		if (slidingLayout != null && !slidingLayout.isPanelExpanded()) {
			slidingLayout.expandPanel();
		}
	}

	public void updateListUserInRoom(String message) {
		if (message != null) {
			userData.addAll(User.fromJsonArrayToUsers(message));
		}
		userAdapter.notifyDataSetChanged();
		ChatService.getInstance().setEnterLeftRoomListener();
	}

	public void onUserEnteredRoom(String id) {
		for (User user : userData) {
			if (id.equals(Integer.toString(user.getUserID()))) {
				return;
			}
		}
		List<String> userIDs = new ArrayList<String>();
		userIDs.add(id);
		ChatService.getInstance().getUserByIds(userIDs, 1, 50);
	}

	public void onUserLeftRoom(String id) {
		Iterator<User> user = userData.iterator();
		while (user.hasNext()) {
			User mUser = (User) user.next();
			if (id.equals(Integer.toString(mUser.getUserID()))) {
				user.remove();
			}
		}
		userAdapter.notifyDataSetChanged();
	}

	private void showSayHi() {
		final SayHiDialogFragment dialog = new SayHiDialogFragment();
		dialog.setCancelable(false);
		dialog.setOnSayHiDialogFragment(new OnSayHiDialogFragment() {

			@Override
			public void onCancel() {
				// findFriendChat();
				sendChatToRoom();
			}
		});
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.add(dialog, "SayHiDialogFragment");
		transaction.commitAllowingStateLoss();
	}

	private void updateInfoInRoom() {
		// Send message update room to user in room
		ChatService.getInstance().sendMessageChatRoom(
				DataManager.getInstance(this).getUser().toJson(),
				MsgType.UPDATE_INFO);
	}

	private void updateUserInfoInRoomStatus(User userInfoUpdated) {
		if (!isAcceptUserRoomInfoUpdate) {
			return;
		}
		for (User user : userData) {
			if (user.getUserID().equals(userInfoUpdated.getUserID())) {
				user.setName(userInfoUpdated.getName());
				UserInfo userInfo = new UserInfo();
				userInfo.setAvatarURL(userInfoUpdated.getUserInfo()
						.getAvatarURL());
				userInfo.setStatus(userInfoUpdated.getUserInfo().getStatus());
				user.setUserInfo(userInfo);
				break;
			}
		}
		userAdapter.notifyDataSetChanged();
	}

	// MESSAGE FRAGMENT
	private View getMessagesView() {
		View view = getLayoutInflater().inflate(R.layout.fragment_messages,
				null);
		findViewIdsMessageFragment(view);
		initMessageFragment();
		return view;
	}

	private void initMessageFragment() {
		historyMessageAdapter = new HistoryMessageAdapter(this,
				historyMessageData);
		lvMessages.setAdapter(historyMessageAdapter);
		loadMessageFromDatabase();
	}

	private void findViewIdsMessageFragment(View view) {
		lvMessages = (ListView) view.findViewById(R.id.lv_messages);
		btLogout = (Button) view.findViewById(R.id.bt_logout);
		tvNameRoomMessageHistory = (TextView) view.findViewById(R.id.tv_name);
		tvMessageRoomMessageHistory = (TextView) view
				.findViewById(R.id.tv_message);
		tvMessageNumRoomMessageHistory = (TextView) view
				.findViewById(R.id.tv_message_num);
		llRoomMessageHistory = (LinearLayout) view
				.findViewById(R.id.ll_room_message_history);
		btSetting = (Button) view.findViewById(R.id.bt_setting);
	}

	private void loadMessageFromDatabase() {
		historyMessageData.clear();
		historyMessageData.addAll(MessagesDataManager.getInstance(this)
				.getAllHistoryMessages(0, 50));
		historyMessageAdapter.notifyDataSetChanged();
		updateNewMessagesNum();
	}

	private void updateNewMessagesNum() {
		int newMessagesNum = 0;
		for (HistoryMessage historyMessage : historyMessageData) {
			newMessagesNum = newMessagesNum + historyMessage.getUnreadNum();
		}
		if (newRoomMessageHistory > 0) {
			newMessagesNum = newMessagesNum + 1;
		}
		if (newMessagesNum > 9) {
			tvNumMessage.setText("9+");
			tvNumMessage.setVisibility(View.VISIBLE);
		} else if (newMessagesNum > 0) {
			tvNumMessage.setText(Integer.toString(newMessagesNum));
			tvNumMessage.setVisibility(View.VISIBLE);
		} else {
			tvNumMessage.setVisibility(View.GONE);
		}
	}

	private void updateMessageInMessagesFragment(String message) {
		// boolean isExist = false;
		if (message != null) {
			MessageContent msg = MessageContent
					.fromJsonToMessageContent(message);
			// Update HIDE CHAT BAR
			mHideChatBarState = HideChatBarState.CHAT_PRIVATE;
			hideChatUserID = Integer.toString(msg.getFromUserID());
			hideChatUserName = msg.getName();

			if (!msg.getFromUserID().equals(
					DataManager.getInstance(this).getUserID())) {
				if (DataManager.getInstance(this).getVibrationSetting()) {
					long[] pattern = { 0, 100 };
					vibrator.vibrate(pattern, -1);
				}
			}

			if (isFindingChat) {
				showChatPrivate(Integer.toString(msg.getFromUserID()),
						msg.getName(), true);
				isFindingChat = false;
				hideNotice();
			}

			// Update HISTORY CHAT
			for (int i = 0; i < historyMessageData.size(); i++) {
				HistoryMessage historyMessage = historyMessageData.get(i);
				if (historyMessage.getMessageContent().getFromUserID()
						.equals(msg.getFromUserID())) {
					// exist ->update
					int num = historyMessage.getUnreadNum() + 1;
					historyMessage.setMessageContent(msg);
					historyMessage.setUnreadNum(num);
					Collections.swap(historyMessageData, i, 0);
					historyMessageAdapter.notifyDataSetChanged();
					MessagesDataManager.getInstance(this).updateHistoryMessage(
							msg.getFromUserID(), msg, num);
					updateNewMessagesNum();
					return;
				}
			}
			// NOTICE: NOT WRITE CODE BELOW HERE, IT MAY BE NOT RUN BY "RETURN"
			// not exist insert new
			HistoryMessage historyMessage = new HistoryMessage();
			historyMessage.setMessageContent(msg);
			historyMessage.setUnreadNum(1);
			historyMessageData.add(0, historyMessage);
			historyMessageAdapter.notifyDataSetChanged();
			MessagesDataManager.getInstance(this).insertHistoryMessage(
					msg.getFromUserID(), msg, 1, false);
			updateNewMessagesNum();
			// NOTICE: NOT WRITE CODE BELOW HERE, IT MAY BE NOT RUN BY "RETURN"
		}

	}

	private void resetUnreadNumMessageFragment(Integer userID) {
		for (HistoryMessage historyMessage : historyMessageData) {
			if (historyMessage.getMessageContent().getFromUserID()
					.equals(userID)) {
				historyMessage.setUnreadNum(0);
				historyMessageAdapter.notifyDataSetChanged();
				break;
			}
		}
		MessagesDataManager.getInstance(this).resetHistoryMessageUnreadNum(
				userID);
		updateNewMessagesNum();
	}

	// CHAT PRIVATE
	private void updateListMessageInChatPrivate(String message) {
		if (message != null) {
			MessageContent messageContent = MessageContent
					.fromJsonToMessageContent(message);
			messageContentPrivateData.add(messageContent);

			chatPrivateAdapter.notifyDataSetChanged();

			// Update HIDE CHAT BAR
			mHideChatBarState = HideChatBarState.CHAT_PRIVATE;

			if (!messageContent.getFromUserID().equals(
					DataManager.getInstance(this).getUserID())) {
				if (DataManager.getInstance(this).getVibrationSetting()) {
					long[] pattern = { 0, 100 };
					vibrator.vibrate(pattern, -1);
				}
				hideChatUserID = Integer.toString(messageContent
						.getFromUserID());
				hideChatUserName = messageContent.getName();
			}
		}

	}

	private void findFriendChat() {
		hideDrawerMessages();
		isFindingChat = true;
		showNotice(true, "Finding chat friend...", "Cancel");
		tvAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isFindingChat = false;
				hideNotice();
			}
		});
		Collections.shuffle(userData);
		int numUserFindChat = 0;
		List<Integer> userInChatting = new ArrayList<Integer>();
		userInChatting.add(DataManager.getInstance(this).getUserID());
		for (HistoryMessage historyMessage : historyMessageData) {
			userInChatting.add(historyMessage.getMessageContent()
					.getFromUserID());
		}
		Random r = new Random();
		final String message = Common.listHiChatNormar[r
				.nextInt(Common.listHiChatNormar.length)];
		for (User user : userData) {
			if (!userInChatting.contains(user.getUserID())) {
				numUserFindChat++;
				ChatService.getInstance().sendMessage(user.getUserID(),
						message, MsgType.TEXT);
			}
			if (numUserFindChat >= 5) {
				return;
			}
		}
		// If time out auto chat
		// ChatService.getInstance().randomAutoMessageContent();

		new CountDownTimer(FIND_FRIEND_TIME_OUT, 1000) {
			@Override
			public void onTick(long millisUntilFinished) {
				if (!isFindingChat) {
					this.cancel();
				}
			}

			@Override
			public void onFinish() {
				if (isFindingChat) {
					// ChatService.getInstance().sendAutoChat(message, false);
					findFriendChat();
				}
			}
		}.start();
	}

	private void sendChatToRoom() {
		ChatService.getInstance().sendMessageChatRoom(
				DataManager.getInstance(this).getUserStatus(), MsgType.TEXT);
	}

	private void showExitDialog() {
		Random rnd = new Random();
		int random = rnd.nextInt(3);
		if ((!DataManager.getInstance(this).isRatedApp()) && (random == 2)) {
			final RateAppDialogFragment dialog = new RateAppDialogFragment();
			FragmentTransaction transaction = getSupportFragmentManager()
					.beginTransaction();
			transaction.add(dialog, "RateAppDialogFragment");
			transaction.commitAllowingStateLoss();
		} else {
			isExit = true;
			final ExitConfirmDialogFragment dialog = new ExitConfirmDialogFragment();
			dialog.setCancelable(false);
			dialog.setOnExitDialogListener(new OnExitDialogListener() {

				@Override
				public void onCancel() {
					isExit = false;
				}

				@Override
				public void onExit() {
					finish();
				}
			});
			FragmentTransaction transaction = getSupportFragmentManager()
					.beginTransaction();
			transaction.add(dialog, "ExitConfirmDialogFragment");
			transaction.commitAllowingStateLoss();
		}
	}

	protected void hideDrawerMessages() {
		if (mDrawerMessages.isMenuVisible()) {
			mDrawerMessages.toggleMenu();
		}
	}

	private void sendImageChat(String url) {
		if (url != null) {

			if (mDisplayState == MainDisplayState.CHAT_ROOM) {
				// Chat room
				ChatService.getInstance().sendMessageChatRoom(url,
						MsgType.IMAGE);
				lvChat.setSelection(chatPrivateAdapter.getCount() - 1);

			} else if (mDisplayState == MainDisplayState.CHAT_PRIVATE) {
				// Chat private
				String sendTo = DataManager.getInstance(this)
						.getCurrentChatUserId();
				if (sendTo == null) {
					return;
				}
				ChatService.getInstance().sendMessage(Integer.parseInt(sendTo),
						url, MsgType.IMAGE);
				lvChat.setSelection(chatRoomAdapter.getCount() - 1);
			} else {
				return;
			}

		}
	}

	private void showNotice(boolean isShowProgessbar, String message,
			String action) {
		if (isShowProgessbar) {
			pbLoading.setVisibility(View.VISIBLE);
		} else {
			pbLoading.setVisibility(View.GONE);
		}
		if (message != null) {
			tvNotice.setText(message);
		}
		if (action != null) {
			tvAction.setText(action);
			tvAction.setVisibility(View.VISIBLE);
			vSplit.setVisibility(View.VISIBLE);
		} else {
			tvAction.setVisibility(View.GONE);
			vSplit.setVisibility(View.GONE);
		}

		llNotice.setVisibility(View.VISIBLE);
		llNotice.startAnimation(animationShow);
	}

	private void hideNotice() {
		animationHide.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				llNotice.setVisibility(View.GONE);
			}
		});
		llNotice.startAnimation(animationHide);
	}

	protected void showEditProfileFragment() {
		final EditProfileDialogFragment dialog = new EditProfileDialogFragment();
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.add(dialog, "EditProfileDialogFragment");
		transaction.commitAllowingStateLoss();
	}

	protected void showSettingFragment() {
		hideDrawerMessages();
		final SettingDialogFragment dialog = new SettingDialogFragment();
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.add(dialog, "SettingDialogFragment");
		transaction.commitAllowingStateLoss();
	}

	protected void showChooseImageFragment() {
		final ChooseImageDialogFragment dialog = new ChooseImageDialogFragment();
		dialog.setOnChooseImageDialogFragment(new OnChooseImageDialogFragment() {

			@Override
			public void onGallery() {
				selectImageFromGallery();
			}

			@Override
			public void onCamera() {
				selectImageFromCamera();
			}
		});
		FragmentTransaction transaction = getSupportFragmentManager()
				.beginTransaction();
		transaction.add(dialog, "ChooseImageDialogFragment");
		transaction.commitAllowingStateLoss();
	}

	protected void selectImageFromGallery() {
		Intent intent = new Intent(this, ProcessImage.class);
		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, false);
		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 0);
		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 0);
		startActivityForResult(intent, Common.RequestCode.CHAT_IMAGE);
	}

	protected void selectImageFromCamera() {
		Intent intent = new Intent(this, ProcessImage.class);
		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, true);
		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 0);
		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 0);
		startActivityForResult(intent, Common.RequestCode.CHAT_IMAGE);
	}

}
